package org.example.shardiing;


import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zengxiaoyu
 * @date 2025/7/10 20:00
 */

public class DatabaseMetaDTO {
    private String logicName;
    private String jdbcUrl;
    private String actualName;
    private DbTemplate dbTemplate;

    public DatabaseMetaDTO(String logicName, String jdbcUrl, DbTemplate dbTemplate) {
        this.logicName = logicName;
        this.jdbcUrl = jdbcUrl;
        this.actualName = extractDatabaseName(jdbcUrl);
        this.dbTemplate = dbTemplate;
    }

    public DatabaseMetaDTO() {
    }


    private static final Pattern DB_NAME_PATTERN =
            Pattern.compile("jdbc:[a-zA-Z]{1,20}://[^/]+/([^?]+)");

    public static String extractDatabaseName(String jdbcUrl) {
        if (jdbcUrl == null || jdbcUrl.trim().isEmpty()) {
            throw new IllegalArgumentException("JDBC URL不能为空");
        }

        Matcher matcher = DB_NAME_PATTERN.matcher(jdbcUrl);
        if (matcher.find()) {
            String group = matcher.group();
            if (group != null && group.contains("/")) {
                int index= group.lastIndexOf("/");
                return group.substring(index+1).trim();
            }
        }
        throw new IllegalArgumentException("无效的JDBC URL格式: " + jdbcUrl);
    }

    public String getLogicName() {
        return logicName;
    }

    public void setLogicName(String logicName) {
        this.logicName = logicName;
    }

    public String getJdbcUrl() {
        return jdbcUrl;
    }

    public void setJdbcUrl(String jdbcUrl) {
        this.jdbcUrl = jdbcUrl;
    }

    public String getActualName() {
        return actualName;
    }

    public void setActualName(String actualName) {
        this.actualName = actualName;
    }

    public DbTemplate getDbTemplate() {
        return dbTemplate;
    }

    public void setDbTemplate(DbTemplate dbTemplate) {
        this.dbTemplate = dbTemplate;
    }

    public static void main(String[] args) {
        org.apache.ibatis.type.JdbcType  jdbcType = JdbcType.valueOf("bigint");
        TypeHandler<?> typeHandler = new TypeHandlerRegistry().getTypeHandler(jdbcType);
        System.out.println(typeHandler);
    }
}
